﻿namespace AccessWebCam
{
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Navigation;

    /// <summary>
    /// Home page for the application.
    /// </summary>
    public partial class Home : Page
    {
        private CaptureSource capSource;

        /// <summary>
        /// Creates a new <see cref="Home"/> instance.
        /// </summary>
        public Home()
        {
            InitializeComponent();

            this.Title = ApplicationStrings.HomePageTitle;

            // Getting devices
            VideoSources.ItemsSource =
                CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();
            AudioSources.ItemsSource =
                CaptureDeviceConfiguration.GetAvailableAudioCaptureDevices();

            capSource = new CaptureSource();

            capSource.CaptureImageCompleted += (sndr, ea) =>
            {
                var bmp = ea.Result;
                var dctx = new Web.Services.CaptureDomainContext();
                dctx.SaveImage(bmp.Pixels);
            };
        }

        /// <summary>
        /// Executes when the user navigates to this page.
        /// </summary>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void Button_Click_1(object sender, System.Windows.RoutedEventArgs e)
        {
            if (capSource != null)
            {
                capSource.Stop();
                capSource.VideoCaptureDevice =
                    (VideoCaptureDevice)VideoSources.SelectedItem;
                capSource.AudioCaptureDevice =
                    (AudioCaptureDevice)AudioSources.SelectedItem;
                VideoBrush vidBrush = new VideoBrush();
                vidBrush.SetSource(capSource);

                WebcamCapture.Fill = vidBrush;

                if (CaptureDeviceConfiguration.AllowedDeviceAccess ||
                    CaptureDeviceConfiguration.RequestDeviceAccess())
                {
                    capSource.Start();
                }
            }
        }

        private void Button_Click_2(object sender, System.Windows.RoutedEventArgs e)
        {
            if (capSource != null)
            {
                capSource.CaptureImageAsync();
            }
        }
    }
}